// 页面路径：store/index.js 
import { createStore } from 'vuex'
import { dict } from '@/utils/api/index.js'
import { land } from '@/utils/api/index.js'
import { warehouse } from '@/utils/api/index.js'
import { getPermissionInfo } from '@/utils/api/user.js'

// 创建 store 实例
const store = createStore({
	state: {
		// 存放状态
		counter: 0,
		// 字典数据
		dictionaries: {},
		// 字典加载状态
		dictLoading: false,
		// 地块数据
		parcelData: null,
		// 地块数据加载状态
		parcelLoading: false,
		// 用户信息
		userInfo: {
			id: '',
			username: '',
			nickname: '',
			avatar: '/static/images/avatar.png',
			role: '',
			phone: '',
			email: '',
			roles: [],
		},
		// 用户信息加载状态
		userInfoLoading: false,
		// 仓库数据
		warehouseData: [],
		// 仓库数据加载状态
		warehouseLoading: false
	},
	mutations: {
		// 更改状态的方法
		increment(state) {
			state.counter++
		},
		decrement(state) {
			state.counter--
		},
		// 设置字典数据
		SET_DICT_DATA(state, { type, data }) {
			state.dictionaries[type] = data
		},
		// 设置字典加载状态
		SET_DICT_LOADING(state, status) {
			state.dictLoading = status
		},
		// 设置地块数据
		SET_PARCEL_DATA(state, data) {
			state.parcelData = data
		},
		// 设置地块加载状态
		SET_PARCEL_LOADING(state, status) {
			state.parcelLoading = status
		},
		// 设置用户信息
		SET_USER_INFO(state, userInfo) {
			state.userInfo = userInfo
		},
		// 设置用户信息加载状态
		SET_USER_INFO_LOADING(state, status) {
			state.userInfoLoading = status
		},
		// 清除用户信息
		CLEAR_USER_INFO(state) {
			state.userInfo = {
				id: '',
				username: '',
				nickname: '',
				avatar: '/static/images/avatar.png',
				role: '',
				phone: '',
				email: '',
				roles: [],
			}
		},
		// 设置仓库数据
		SET_WAREHOUSE_DATA(state, data) {
			state.warehouseData = data
		},
		// 设置仓库加载状态
		SET_WAREHOUSE_LOADING(state, status) {
			state.warehouseLoading = status
		}
	},
	actions: {
		// 异步操作
		asyncIncrement({ commit }) {
			setTimeout(() => {
				commit('increment')
			}, 1000)
		},
		// 获取字典数据
		async getDictByType({ commit, state }, type) {
			// 如果已经加载过该类型的字典，直接返回
			if (state.dictionaries[type]) {
				return state.dictionaries[type]
			}
			
			commit('SET_DICT_LOADING', true)
			try {
				const res = await dict.getDictDataByType(type)
				if (res.code === 0 && res.data) {
					commit('SET_DICT_DATA', { type, data: res.data })
					return res.data
				}
				return []
			} catch (error) {
				console.error('获取字典数据失败:', error)
				return []
			} finally {
				commit('SET_DICT_LOADING', false)
			}
		},
		// 获取所有字典类型
		async getAllDictTypes({ commit }) {
			commit('SET_DICT_LOADING', true)
			try {
				const res = await dict.getAllDictTypes()
				console.log('获取所有字典类型：');
				console.log(res);
				if (res.code === 0 && res.data) {
					// 处理所有字典数据
					res.data.forEach(dictType => {
						if (dictType.type && dictType.listDictData) {
							commit('SET_DICT_DATA', { 
								type: dictType.type, 
								data: dictType.listDictData 
							})
						}
					})
					return res.data
				}
				return []
			} catch (error) {
				console.error('获取所有字典类型失败:', error)
				return []
			} finally {
				commit('SET_DICT_LOADING', false)
			}
		},
		// 获取地块数据
		async fetchParcelData({ commit, state }, forceRefresh = false) {
			// 如果已经加载过数据且不需要强制刷新，直接返回缓存数据
			if (state.parcelData && !forceRefresh) {
				return state.parcelData
			}
			
			commit('SET_PARCEL_LOADING', true)
			try {
				const res = await land.getAllParcelAndFields()
				if (res.code === 0 && res.data) {
					commit('SET_PARCEL_DATA', res.data)
					return res.data
				}
				return null
			} catch (error) {
				console.error('获取地块数据失败:', error)
				return null
			} finally {
				commit('SET_PARCEL_LOADING', false)
			}
		},
		// 清除地块数据
		clearParcelData({ commit }) {
			commit('SET_PARCEL_DATA', null)
		},
		// 获取用户信息
		async fetchUserInfo({ commit, state }, forceRefresh = false) {
			// 如果已经有用户信息且不需要强制刷新，直接返回
			if (state.userInfo.username && !forceRefresh) {
				return state.userInfo
			}
			
			commit('SET_USER_INFO_LOADING', true)
			try {
				const res = await getPermissionInfo()
				if (res.code === 0 && res.data && res.data.user) {
					const userData = res.data.user
					const userInfo = {
						id: userData.id || '',
						username: userData.username || '',
						nickname: userData.nickname || '',
						avatar: '/static/images/avatar.png',
						role: res.data.roles && res.data.roles.length > 0 ? res.data.roles[0] : '',
						phone: userData.mobile || '',
						email: userData.email || '',
						roles: res.data.roles || [],
						// roles: [],
					}
					commit('SET_USER_INFO', userInfo)
					return userInfo
				}
				return null
			} catch (error) {
				console.error('获取用户信息失败:', error)
				return null
			} finally {
				commit('SET_USER_INFO_LOADING', false)
			}
		},
		// 清除用户信息
		clearUserInfo({ commit }) {
			commit('CLEAR_USER_INFO')
		},
		// 获取仓库数据
		async fetchWarehouseData({ commit, state }, forceRefresh = false) {
			// 如果已经加载过数据且不需要强制刷新，直接返回缓存数据
			if (state.warehouseData.length > 0 && !forceRefresh) {
				return state.warehouseData
			}

			commit('SET_WAREHOUSE_LOADING', true)
			try {
				const res = await warehouse.getWarehouseList({
					pageNo: 1,
					pageSize: 99,
					status: 1 // 只获取启用状态的仓库
				})

				if (res.code === 0 && res.data) {
					commit('SET_WAREHOUSE_DATA', res.data)
					return res.data
				}
				return []
			} catch (error) {
				console.error('获取仓库数据失败:', error)
				return []
			} finally {
				commit('SET_WAREHOUSE_LOADING', false)
			}
		},
		// 清除仓库数据
		clearWarehouseData({ commit }) {
			commit('SET_WAREHOUSE_DATA', [])
		}
	},
	getters: {
		// 计算属性
		currentCounter(state) {
			return state.counter
		},
		// 获取指定类型的字典数据
		getDictByType: (state) => (type) => {
			return state.dictionaries[type] || []
		},
		// 将字典值转换为标签
		getDictLabel: (state) => (type, value) => {

			const dictList = state.dictionaries[type] || []
			const item = dictList.find(dict => dict.value == value)
			return item ? item.label : value
		},
		// 获取地块数据
		getParcelData(state) {
			return state.parcelData
		},
		// 获取地块加载状态
		getParcelLoading(state) {
			return state.parcelLoading
		},
		// 获取用户信息
		getUserInfo(state) {
			return state.userInfo
		},
		// 获取用户信息加载状态
		getUserInfoLoading(state) {
			return state.userInfoLoading
		},
		// 判断是否是管理员
		isManager(state) {
			return state.userInfo.roles.includes('super_admin')
		},
		// 获取仓库数据
		getWarehouseData(state) {
			return state.warehouseData
		},
		// 获取仓库加载状态
		getWarehouseLoading(state) {
			return state.warehouseLoading
		},
		// 获取仓库名称下拉数据
		getWarehouseSelectData(state) {
			return state.warehouseData.map(item => ({
				value: item.id,
				text: item.warehouseName
			}))
		},
		// 根据仓库ID获取仓库名称
		getWarehouseNameById: (state) => (warehouseId) => {
			console.log('根据仓库ID获取仓库名称')
			console.log(state.warehouseData)
			console.log(warehouseId)
			const warehouse = state.warehouseData.find(item => item.id == warehouseId)
			return warehouse ? warehouse.warehouseName : '未知仓库'
		},
		// 根据仓库ID获取库位下拉数据
		getLocationSelectDataByWarehouseId: (state) => (warehouseId) => {
			const warehouse = state.warehouseData.find(item => item.id === warehouseId)
			if (warehouse && warehouse.listAppStorageLocation) {
				return warehouse.listAppStorageLocation.map(location => ({
					value: location.locationId,
					text: location.locationName
				}))
			}
			return []
		},
		// 根据库位ID获取库位名称
		getLocationNameById: (state) => (locationId) => {
			for (const warehouse of state.warehouseData) {
				if (warehouse.listAppStorageLocation) {
					const location = warehouse.listAppStorageLocation.find(loc => loc.locationId === locationId)
					if (location) {
						return location.locationName
					}
				}
			}
			return '未知库位'
		},
		// 根据库位ID获取仓库名称
		getWarehouseNameByLocationId: (state) => (locationId) => {
			for (const warehouse of state.warehouseData) {
				if (warehouse.listAppStorageLocation) {
					const location = warehouse.listAppStorageLocation.find(loc => loc.locationId === locationId)
					if (location) {
						return warehouse.warehouseName
					}
				}
			}
			return '未知仓库'
		}
	}
})

export default store